package com.example.dense_rack_server.service.dataBackup;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dense_rack_server.entity.BackupTask;
import com.example.dense_rack_server.mapper.dataBackup.BackupTaskMapper;
import com.example.dense_rack_server.utils.DataBackup.quartz.QuartzManager;
import com.example.dense_rack_server.utils.ResponseModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 备份任务信息 服务实现类
 * </p>
 *
 * @author  张彬 
 * @since 2025-07-01
 */
@Service
public class BackupTaskService extends ServiceImpl<BackupTaskMapper, BackupTask> {

    @Resource
    public BackupTaskMapper backupTaskMapper;
    @Autowired
    private QuartzManager quartzManager;

    /**
     * 获取备份管理列表
     */
    public Map<String, Object> tableList(int page, int limit, String nodeId, String status) {

        Map<String, Object> paramsMap = new HashMap<>();
        // 手动处理分页
        int offset = (page - 1) * limit;
        paramsMap.put("page", offset);
        paramsMap.put("limit", limit);
        if (StrUtil.isNotEmpty(nodeId)) {
            paramsMap.put("node_id", nodeId);
        }
        if (StrUtil.isNotEmpty(status)) {
            paramsMap.put("status", status);
        }
        List<Map<String, Object>> mapList = backupTaskMapper.tableList(paramsMap);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "数据请求成功");
        map.put("count", backupTaskMapper.tableListCount(paramsMap));
        map.put("data", mapList);
        return map;
    }


    /**
     * 修改定时任务状态
     */
    public ResponseModel changeStatus(JSONObject data) {
        BackupTask backupTask = backupTaskMapper.selectById(data.getInt("id"));
        backupTask.setStatus(data.getBool("status"));
        backupTaskMapper.updateById(backupTask);
        if (data.getInt("status") == 0) {
            quartzManager.stop(backupTask.getId());
            return ResponseModel.success("禁用成功");
        } else {
            quartzManager.start(backupTask.getId());
            return ResponseModel.success("启用成功");
        }
    }
}
